package com.hmdp.init;

import com.hmdp.service.IShopService;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;  

@Component  
public class MyStartupRunner {

    @Autowired
    RedissonClient redisson;

    @Autowired
    IShopService shopService;


    /** 预计插入的数据 */
    private static final Integer expectedInsertions = 100;
    /** 误判率 */
    private static final Double fpp = 0.0001;

    @EventListener(ApplicationReadyEvent.class)
    @Bean
    public RBloomFilter<Long> bloomFilter() {
        //1.创建BloomFilter,并初始化
        RBloomFilter<Long> bloomFilter = redisson.getBloomFilter("ShopIdFilter");
        bloomFilter.tryInit(expectedInsertions, fpp);
        //2.利用shopService从数据库获取shopId
        //3.将数据插入BloomFilter
        shopService.list().forEach(shop -> {
            bloomFilter.add(shop.getId());
        });
        return bloomFilter;
    }
}